package me.payge.video;

import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.util.Log;
import android.view.Surface;

import java.io.IOException;

public class VideoRecorder implements Camera.PreviewCallback {

    private Camera mCamera;
    private SurfaceTexture mSurfaceTexture;
    private float[] mTextureMatrix = new float[16];

    public native void create(Surface surface, int width, int height);

    private native void onFrameAvailable();

    private void startPreviewFromNative(int textureId) {
        mSurfaceTexture = new SurfaceTexture(textureId);
        mCamera = Camera.open();
        Camera.Parameters params = mCamera.getParameters();
        params.setPreviewFormat(ImageFormat.NV21);
        mCamera.setPreviewCallback(this);
        mCamera.setDisplayOrientation(90);
        try {
            mCamera.setPreviewTexture(mSurfaceTexture);
            mCamera.startPreview();
        } catch (IOException e) {
            Log.w("err",  e);
            destroy();
        }
    }

    private void updateTexImageFromNative() {
        mSurfaceTexture.updateTexImage();
    }

    private float[] getTextureMatrix() {
        mSurfaceTexture.getTransformMatrix(mTextureMatrix);
        return mTextureMatrix;
    }

    private void releaseCameraFromNative() {
        Log.d("AvSdk", "video recorder releaseCameraFromNative");
        mCamera.setPreviewCallback(null);
        mCamera.stopPreview();
        mCamera.release();
        mSurfaceTexture = null;
    }

    public void destroy() {
        Log.d("AvSdk", "video recorder destroy");
        release();
    }

    private native void release();

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        //mSurfaceTexture.updateTexImage();
        onFrameAvailable();
    }
}
